/*
 * Copyright (c) 2015. 速位中国
 */

package com.commons;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * Created with ZhaoJianji.
 * Date: 2015/9/25
 * 如果你看到这个，那么说明你现在已经在负责我以前的项目了。我感到非常抱歉。愿上帝保佑你。
 */
public class MD5Util {
    public static final String KEY_MD5 = "MD5";
    public static final String SALT_VALUE = "URwdSarm4s9ZFtSH2n9WvSLiW2AYxDab";
    /**
     * MD5加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data)  {
        byte[] result = null;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(KEY_MD5);
            md5.update(data);
            result = md5.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;

    }

    public static String encryptMD5(int time, short linkId,int terminalId,int password){
        byte[] salt = SALT_VALUE.getBytes(Charset.forName("UTF-8"));
        byte[] bytes = new byte[13 + salt.length];
        bytes[0] = (byte)linkId;
        byte[] timeBytes = TypeConvert.getBytes(time,true);
        System.arraycopy(timeBytes, 0, bytes, 1, timeBytes.length);
        System.arraycopy(salt,0,bytes,5,salt.length);
        byte[] ids = TypeConvert.getBytes(terminalId,true);
        byte[] pwds = TypeConvert.getBytes(password,true);
        System.arraycopy(ids,0,bytes,5 + salt.length,ids.length);
        System.arraycopy(pwds,0,bytes,9 + salt.length,pwds.length);

        return StrConvert.bytes2Hex(encrypt(bytes));


    }

    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }



}
